﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JYH.Data;
using Newtonsoft.Json;
using JYH.Model;
using JYH.DataAccess;
using JYH.Framework;
using JYH.Model.API;

namespace JYH.Business
{
    /// <summary>
    ///  WmsTradebarcode
    /// </summary>
    public class WmsTradebarcodeBLL : BusinessBase<WmsTradebarcode>
    {
        /// <summary>
        ///  WmsTradebarcode
        /// </summary>
        public WmsTradebarcodeBLL()
        {
            myDataBase = DB.D();
            this.SqlSelect = @"; Select WmsTradebarcode.*,BasBarcodeInfo.BarcodeNO,BasBarcodeInfo.BatchNO,WmsTradeOrderInfo.TradeOrderNO,
                                           BasMaterialInfo.MaterialNO,BasMaterialInfo.MaterialName,BasMaterialInfo.MaterialDesc,
                                           BasStorageInfo.StorageNO,BasWarehouseInfo.WarehouseNO,BasWarehouseInfo.WarehouseID,
						                   BasLampInfo.LampNO,BasRackInfo.RackNO,
                                           BasWarehouseInfo.WarehouseName,BasMaterialInfo.MaterialID,BasLampInfo.LampCode,
										   ToStorageInfo.StorageNO ToStorageNO,ToWarehouseInfo.WarehouseNO ToWarehouseNO,
										   ToLampInfo.LampNO ToLampNO,ToRackInfo.RackNO ToRackNO,ToLampInfo.LampCode ToLampCode
                                           From WmsTradebarcode
                                           inner join WmsTradeOrderInfo on WmsTradeOrderInfo.TradeOrderID=WmsTradebarcode.TradeOrderID
                                           inner join BasBarcodeInfo on WmsTradebarcode.BarcodeID=BasBarcodeInfo.BarcodeID
                                           inner join BasMaterialInfo on BasBarcodeInfo.MaterialID=BasMaterialInfo.MaterialID
                                           left join BasStorageInfo on BasStorageInfo.StorageID=WmsTradebarcode.StorageID
                                           left join BasWarehouseInfo on BasWarehouseInfo.WarehouseID=BasStorageInfo.WarehouseID
                                           left join BasLampInfo on BasLampInfo.LampID=WmsTradebarcode.LampID
                                           left join BasRackInfo on BasRackInfo.RackID=BasLampInfo.RackID
										   left join BasStorageInfo ToStorageInfo on ToStorageInfo.StorageID=WmsTradebarcode.ToStorageID
                                           left join BasWarehouseInfo ToWarehouseInfo on ToWarehouseInfo.WarehouseID=ToStorageInfo.WarehouseID
                                           left join BasLampInfo  ToLampInfo on ToLampInfo.LampID=WmsTradebarcode.ToLampID
                                           left join BasRackInfo ToRackInfo on ToRackInfo.RackID=ToLampInfo.RackID";
        }

        /// <summary>
        /// 调拨条码查询
        /// </summary>
        public string DPSelect = @"Select WmsTradebarcode.*,BasBarcodeInfo.BarcodeNO,BasBarcodeInfo.BatchNO,WmsTradeOrderInfo.TradeOrderNO,
                                           BasMaterialInfo.MaterialNO,BasMaterialInfo.MaterialName,BasMaterialInfo.MaterialDesc,
                                           InStr.StorageNO, OutStr.StorageNO ToStorageNO,BasWarehouseInfo.WarehouseNO,BasWarehouseInfo.WarehouseID,
																					 InLamp.LampNO, OutLamp.LampNO ToLampNO,BasRackInfo.RackNO,
                                           BasWarehouseInfo.WarehouseName,BasMaterialInfo.MaterialID,InLamp.LampCode
                                           From WmsTradebarcode
                                           inner join WmsTradeOrderInfo on WmsTradeOrderInfo.TradeOrderID=WmsTradebarcode.TradeOrderID
                                           inner join BasBarcodeInfo on WmsTradebarcode.BarcodeID=BasBarcodeInfo.BarcodeID
                                           inner join BasMaterialInfo on BasBarcodeInfo.MaterialID=BasMaterialInfo.MaterialID
                                           left join BasStorageInfo InStr on InStr.StorageID=WmsTradebarcode.StorageID
																		    	 left join BasStorageInfo OutStr on OutStr.StorageID=WmsTradebarcode.ToStorageID
                                           left join BasWarehouseInfo on BasWarehouseInfo.WarehouseID=InStr.WarehouseID
                                           left join BasLampInfo InLamp on InLamp.LampID=WmsTradebarcode.LampID
																					 left join BasLampInfo OutLamp on OutLamp.LampID=WmsTradebarcode.ToLampID
                                           left join BasRackInfo on BasRackInfo.RackID=InLamp.RackID";

        /// <summary>
        /// 撤销调拨发料条码
        /// </summary>
        /// <param name="info"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public bool DeleteTradeInBarCode(WmsTradebarcode Info, ref ResponseJson<WmsTradebarcode> json)
        {
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                sql = new Sql();
                sql.Append(this.SqlSelect);
                sql.Where($"WmsTradeOrderInfo.TradeOrderNO='{Info.TradeOrderNO}' AND BasBarcodeInfo.BarcodeNO='{Info.BarcodeNO}'");
                var data = db.FirstOrDefault<WmsTradebarcode>(sql);
                if (data == null)
                {
                    json.Message = ErrorCode.NoExistBarcode.GetMessage(Info.BarcodeNO);
                    db.AbortTransaction();
                    return false;
                }
                //更新基础条码状态 IsStock=1
                sb.Append($"Update  BasBarcodeInfo  Set IsStock=1 where  BarcodeID  = '{data.BarcodeID}'");

                sb.Append($"DELETE from WmsTradebarcode where WmsTradebarcode.TradebarcodeID='{data.TradebarcodeID}' ");
                //灯珠 回到实物占用状态
                sb.Append(@"update BasLampInfo Set RState='1' from BasLampInfo
                                      left join WmsStockBarcode on BasLampInfo.LampID=WmsStockBarcode.LampID
                                      left join BasBarcodeInfo on BasBarcodeInfo.BarcodeID=WmsStockBarcode.BarcodeID
                                      where BasBarcodeInfo.BarcodeNO='" + Info.BarcodeNO + "'");
                sql = new Sql();
                WmsTradeSourceBLL tradeSourceBLL = new WmsTradeSourceBLL();
                sql.Append(tradeSourceBLL.SqlSelect);
                sql.Where($"WmsTradeSource.TradeSourceID='{data.TradeSourceID}'");
                var TradeSourceList = db.FirstOrDefault<WmsTradeSource>(sql);
                if (TradeSourceList == null)
                {
                    db.AbortTransaction();
                    json.Message = ErrorCode.WarehouseInfo01.GetMessage(Info.TradeOrderNO);
                    return false;
                }
                TradeSourceList.ActionQty -= data.Qty;
                TradeSourceList.CalculateQty -= data.Qty;
                sb.Append(BusinessTool.GetUpdateSql(TradeSourceList));

                sb.Append($"update BasBarcodeInfo Set IsStock=1 where BarcodeID='{data.BarcodeID}'");
                //解除库存锁定
                sql = new Sql();
                sql.Append(@";  Select WmsStockBarcode.*,WmsStockMaterial.StockMaterialID,BasLampInfo.LampNO,BasBarcodeInfo.BatchNO
                                From WmsStockBarcode
                                Inner JOin BasBarcodeInfo On BasBarcodeInfo.BarcodeID=WmsStockBarcode.BarcodeID
                                Inner JOin WmsStockMaterial On WmsStockBarcode.MaterialID=WmsStockMaterial.MaterialID
                                And WmsStockBarcode.WarehouseID=WmsStockMaterial.WarehouseID
                                And WmsStockBarcode.StorageID=WmsStockMaterial.StorageID
                                And BasBarcodeInfo.BatchNO=WmsStockMaterial.BatchNO
							    Left JOin BasLampInfo On WmsStockBarcode.LampID=BasLampInfo.LampID");
                sql.Where($"BasBarcodeInfo.BarcodeID ='{data.BarcodeID}'");
                sql.OrderBy(" BasBarcodeInfo.BarcodeNO");
                var StockBarcodelist = db.FirstOrDefault<WmsStockBarcode>(sql);
                if (StockBarcodelist == null)
                {
                    db.AbortTransaction();
                    json.Message = ErrorCode.WarehouseInfo01.GetMessage(data.BarcodeNO);
                    return false;
                }
                StockBarcodelist.IsLock = 0;
                sb.Append(BusinessTool.GetUpdateSql(StockBarcodelist));

                if (sb.Length > 0)
                    db.Execute(sb.ToString());
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }

        /// <summary>
        /// 备料明细确认
        /// </summary>
        /// <param name="lists"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool GetStationCode(ref List<WmsTradebarcode> lists, ref ResponseJson<WmsTradebarcode> json)
        {
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                string tradeIDs = "'',";
                foreach (var item in lists)
                {
                    tradeIDs += "'" + item.TradebarcodeID + "',";
                }
                tradeIDs = tradeIDs.Substring(0, tradeIDs.Length - 1);
                // 更新tradebarcode
                sb.Append($"Update  WmsTradebarcode  Set RState=2 where  TradebarcodeID  in ({tradeIDs})");
                if (sb.Length > 0) { db.Execute(sb.ToString()); }
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }

            db.CompleteTransaction();
            return true;
        }

        /// <summary>
        /// 调拨上架撤销
        /// </summary>
        /// <param name="info"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteCode_5(WmsTradebarcode info, ref ResponseJson<WmsTradebarcode> json)
        {
            WmsStockBarcodeBLL wmsStockBarcodeBLL = new WmsStockBarcodeBLL();
            ResponseJson<WmsStockBarcode> response = new ResponseJson<WmsStockBarcode>();
            List<WmsStockBarcode> lists = new List<WmsStockBarcode>();
            WmsStockBarcode wmsStock = new WmsStockBarcode();
            wmsStock.BarcodeNO = info.BarcodeNO;
            lists.Add(wmsStock);
            if (!wmsStockBarcodeBLL.OutMaterialBarcode(ref lists, true, ref response))
            {
                json.Message = response.Message;
                return false;
            }
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            try
            {
                WmsTradebarcodeBLL OrderInfoBLL = new WmsTradebarcodeBLL();
                sql = new Sql();
                sql.Append(OrderInfoBLL.SqlSelect);
                sql.Append($"Where WmsTradeOrderInfo.TradeOrderNO='{info.TradeOrderNO}' ");
                sql.Append($"Where BasBarcodeInfo.BarcodeNO ='{info.BarcodeNO}'");
                var barcode = OrderInfoBLL.myDataBase.FirstOrDefault<WmsTradebarcode>(sql);
                if (barcode == null)
                {
                    json.Message = ErrorCode.Delete.GetMessage(info.BarcodeNO);
                    db.AbortTransaction();
                    return false;
                }
                barcode.RState = "2";
                db.Execute(BusinessTool.GetUpdateSql(barcode));
            }
            catch (Exception ex)
            {
                json.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }
    }
}